# -*- coding: utf-8 -*-
# @Time    : 2024/4/2 13:51
# @Author  : CHNJX
# @File    : nvr_reboot.py
# @Desc    : NVR每隔半分钟重启一次
import os
import socket
import telnetlib
import time

# 从环境变量获取配置信息，提高安全性
HOST = os.getenv('TARGET_HOST', '192.168.1.98')
PORT = os.getenv('TARGET_PORT', '23')
USER = os.getenv('TARGET_USER', 'root')
PASSWORD = os.getenv('TARGET_PASSWORD', 'vp202401')
COMMAND = os.getenv('COMMAND', 'reboot')


def send_command():
    try:
        tn = telnetlib.Telnet(HOST, int(PORT))
        tn.read_until(b"login: ")
        tn.write(USER.encode('ascii') + b"\n")
        tn.read_until(b"Password: ")
        tn.write(PASSWORD.encode('ascii') + b"\n")

        tn.write(COMMAND.encode('ascii') + b"\n")

        # 确认命令执行结果
        response = tn.read_all()
        print(f"Device responded after sending command: {response.decode('ascii')}")

        # 增加等待时间以确保设备有足够时间处理重启命令

        tn.write(b"exit\n")
        print("Exit command sent.")
    except socket.timeout as e:
        print(f"Timeout occurred during the process: {e}")
    except Exception as e:
        print(f"Failed to send reboot command: {e}")
    finally:
        tn.close()


if __name__ == "__main__":
    while True:
        send_command()
        time.sleep(60)
